package priv.yiyuan.example.composite.approver2;

import java.util.ArrayList;
import java.util.List;

/**
 * @author YiYuan
 * @data 2025/8/29
 * @apoNote
 */
public class Department implements Approver {

    private String name;

    private List<Approver> employees = new ArrayList<>();

    private Approver nextApprover;

    public Department(String name) {
        this.name = name;
    }

    @Override
    public void handleRequest(LeaveRequest request) {

        boolean handled = false;
        for (Approver employee : employees) {

            if (request.getDays() <= employee.getApprovalLimit()) {
                employee.handleRequest(request);
                handled = true;
                break;
            }

        }

        if (!handled && nextApprover != null) {
            System.out.println(name + " 部门无法处理, 转交给 " + nextApprover.getName());
            nextApprover.handleRequest(request);
        }
        else if (!handled) {
            System.out.println("无人能审批 " + request.getEmployeeName() + " 的 " + request.getDays() + " 天请假申请。");
        }
    }

    @Override
    public void setNextApprover(Approver nextApprover) {

    }

    @Override
    public String getName() {
        return this.name;
    }

    @Override
    public int getApprovalLimit() {
        return employees.stream().mapToInt(Approver::getApprovalLimit).max().orElse(0);
    }

    public void addEmployee(Approver employee) {
        employees.add(employee);
    }

    public void removeEmployee(Approver employee) {
        employees.remove(employee);
    }
}
